const { asyncHandler } = require('../../middleware/errorHandler');
const { success, error, paginate, paginateResponse } = require('../../utils/common');
const { Op } = require('sequelize');
const { sequelize } = require('../../config/database');
const Course = require('../../models/Course');
const User = require('../../models/User');
const logger = require('../../utils/logger');

class StudentCourseController {
  /**
   * 课程列表
   */
  static index = asyncHandler(async (req, res) => {
    const { page = 1, limit = 10, category_id, is_free, is_recommend, is_hot, keyword } = req.query;
    
    const where = { status: 'published' };
    if (category_id) where.category_id = category_id;
    if (is_free !== undefined) where.is_free = is_free === 'true';
    if (is_recommend !== undefined) where.is_recommend = is_recommend === 'true';
    if (is_hot !== undefined) where.is_hot = is_hot === 'true';
    if (keyword) {
      where[Op.or] = [
        { title: { [Op.like]: `%${keyword}%` } },
        { description: { [Op.like]: `%${keyword}%` } }
      ];
    }

    const { offset, limit: pageLimit } = paginate(page, limit);
    
    const { count, rows } = await Course.findAndCountAll({
      where,
      include: [
        {
          model: User,
          as: 'teacher',
          attributes: ['id', 'username', 'nickname', 'avatar']
        }
      ],
      offset,
      limit: pageLimit,
      order: [['created_at', 'DESC']]
    });

    res.json(paginateResponse(rows, count, page, limit));
  });

  /**
   * 课程详情
   */
  static show = asyncHandler(async (req, res) => {
    const { id } = req.params;

    const course = await Course.findOne({
      where: { id, status: 'published' },
      include: [
        {
          model: User,
          as: 'teacher',
          attributes: ['id', 'username', 'nickname', 'avatar', 'bio']
        }
      ]
    });

    if (!course) {
      return res.status(404).json(error('课程不存在'));
    }

    // 增加观看次数
    await course.increment('views_count');

    // 检查学生是否已购买此课程
    const isPurchased = await sequelize.query(
      'SELECT id FROM course_users WHERE course_id = ? AND user_id = ? AND status = 1',
      {
        replacements: [id, req.user.id],
        type: sequelize.QueryTypes.SELECT
      }
    );

    res.json(success({
      ...course.toJSON(),
      isPurchased: isPurchased.length > 0
    }, '获取成功'));
  });

  /**
   * 推荐课程
   */
  static recommend = asyncHandler(async (req, res) => {
    const { limit = 10 } = req.query;

    const courses = await Course.findAll({
      where: { 
        status: 'published',
        is_recommend: true
      },
      include: [
        {
          model: User,
          as: 'teacher',
          attributes: ['id', 'username', 'nickname', 'avatar']
        }
      ],
      limit: parseInt(limit),
      order: [['created_at', 'DESC']]
    });

    res.json(success(courses, '获取成功'));
  });

  /**
   * 热门课程
   */
  static hot = asyncHandler(async (req, res) => {
    const { limit = 10 } = req.query;

    const courses = await Course.findAll({
      where: { 
        status: 'published',
        is_hot: true
      },
      include: [
        {
          model: User,
          as: 'teacher',
          attributes: ['id', 'username', 'nickname', 'avatar']
        }
      ],
      limit: parseInt(limit),
      order: [['views_count', 'DESC']]
    });

    res.json(success(courses, '获取成功'));
  });

  /**
   * 免费课程
   */
  static free = asyncHandler(async (req, res) => {
    const { page = 1, limit = 10 } = req.query;

    const where = { 
      status: 'published',
      is_free: true
    };

    const { offset, limit: pageLimit } = paginate(page, limit);
    
    const { count, rows } = await Course.findAndCountAll({
      where,
      include: [
        {
          model: User,
          as: 'teacher',
          attributes: ['id', 'username', 'nickname', 'avatar']
        }
      ],
      offset,
      limit: pageLimit,
      order: [['created_at', 'DESC']]
    });

    res.json(paginateResponse(rows, count, page, limit));
  });

  /**
   * 我的课程
   */
  static myCourses = asyncHandler(async (req, res) => {
    const { page = 1, limit = 10 } = req.query;

    const { offset, limit: pageLimit } = paginate(page, limit);
    
    // 获取学生购买的课程
    const { count, rows } = await sequelize.query(
      `SELECT c.*, cu.created_at as purchase_time, cu.progress
       FROM courses c
       INNER JOIN course_users cu ON c.id = cu.course_id
       WHERE cu.user_id = ? AND cu.status = 1
       ORDER BY cu.created_at DESC
       LIMIT ? OFFSET ?`,
      {
        replacements: [req.user.id, pageLimit, offset],
        type: sequelize.QueryTypes.SELECT
      }
    );

    const totalCount = await sequelize.query(
      'SELECT COUNT(*) as count FROM course_users WHERE user_id = ? AND status = 1',
      {
        replacements: [req.user.id],
        type: sequelize.QueryTypes.SELECT
      }
    );

    res.json(paginateResponse(rows, totalCount[0].count, page, limit));
  });

  /**
   * 购买课程
   */
  static purchase = asyncHandler(async (req, res) => {
    const { course_id } = req.body;

    if (!course_id) {
      return res.status(400).json(error('课程ID不能为空'));
    }

    // 检查课程是否存在
    const course = await Course.findOne({
      where: { id: course_id, status: 'published' }
    });

    if (!course) {
      return res.status(404).json(error('课程不存在'));
    }

    // 检查是否已购买
    const existingPurchase = await sequelize.query(
      'SELECT id FROM course_users WHERE course_id = ? AND user_id = ?',
      {
        replacements: [course_id, req.user.id],
        type: sequelize.QueryTypes.SELECT
      }
    );

    if (existingPurchase.length > 0) {
      return res.status(400).json(error('您已购买此课程'));
    }

    // 如果是免费课程，直接购买
    if (course.is_free) {
      await sequelize.query(
        'INSERT INTO course_users (course_id, user_id, status, created_at, updated_at) VALUES (?, ?, 1, NOW(), NOW())',
        {
          replacements: [course_id, req.user.id]
        }
      );

      // 增加课程学生数
      await course.increment('students_count');

      logger.info(`学生 ${req.user.id} 购买免费课程: ${course_id}`);

      res.json(success(null, '购买成功'));
      return;
    }

    // TODO: 处理付费课程购买逻辑
    // 这里需要集成支付系统

    res.json(error('付费课程购买功能待实现'));
  });

  /**
   * 课程搜索
   */
  static search = asyncHandler(async (req, res) => {
    const { keyword, page = 1, limit = 10 } = req.query;

    if (!keyword) {
      return res.status(400).json(error('搜索关键词不能为空'));
    }

    const where = { 
      status: 'published',
      [Op.or]: [
        { title: { [Op.like]: `%${keyword}%` } },
        { description: { [Op.like]: `%${keyword}%` } }
      ]
    };

    const { offset, limit: pageLimit } = paginate(page, limit);
    
    const { count, rows } = await Course.findAndCountAll({
      where,
      include: [
        {
          model: User,
          as: 'teacher',
          attributes: ['id', 'username', 'nickname', 'avatar']
        }
      ],
      offset,
      limit: pageLimit,
      order: [['views_count', 'DESC']]
    });

    res.json(paginateResponse(rows, count, page, limit));
  });
}

module.exports = StudentCourseController; 